<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="format-detection" content="telephone=yes" />
    <title>远程蓝牙听诊系统应用端</title>
    <style>
      .title {
        margin: 10px auto;
        font-size: 25px;
      }
      .name {
        margin: 20px auto;
        font-size: 18px;
        /* color: rgb(64, 120, 242) */
      }
      .visualizer{
        width: 80%;
        height:300px;
        margin:20px 10px;
      }
    </style>
  </head>

  <body>
    <div id="container" style="width: 100%; margin: 0 auto">
       <div class="title">远程蓝牙听诊系统应用端</div>
      <div class="name">学生：黄健福</div>
      <button onclick="loadPCM()">开始播放</button>
      <!-- <input
        type="range"
        max="1"
        value="0.1"
        min="0"
        id="range"
        onchange="changeVolume(event)"
        step="0.1"
      /><br /> -->
      <button onclick="pause()">暂停播放</button>
      <button onclick="continuePlay()">继续播放</button>
      <canvas class="visualizer"></canvas>
    </div>

    <script src="./dist/index.js"></script>
    <script>
      let player;
      window.loadPCM = function loadPCM() {
        // var socketURL = 'ws://23.94.99.218:8899';
        // var socketURL = 'ws://localhost:8899';
        var socketURL = 'ws://106.15.126.101:8899';
        // 这是我搭载自己服务器上的server端，用来接收pcm数据
        // 如果起了example里面的本地server端，改成对应的ws地址就行了
        // var socketURL = 'wss://pkjy.xyz/websocket';

        player = new PCMPlayer({
          inputCodec: "Int16",
          channels: 1,
          sampleRate: 8000,
          flushTime: 200,
        });

        //音量设置: 这里不能设置，设置后会有回音
        // player.volume(1)

        var ws = new WebSocket(socketURL);
        ws.binaryType = "arraybuffer";
        ws.addEventListener("message", function (event) {
          // 可以传 ArrayBuffer 或者 任意TypedArray
          console.log("event.data", event.data);
          player.feed(event.data);
        });
        ws.addEventListener("open", function (event) {
          console.log("web ws打开了");
        });
        ws.onerror = function (error) {
          console.error("web WebSocket发生错误:", error);
        };
        ws.onclose = function (event) {
          console.log("web WebSocket连接已关闭", event);
        };

        // 绘制波形图
        const bufferLength = player.analyserNode.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);
        player.analyserNode.getByteTimeDomainData(dataArray);

        function draw() {
          drawVisual = requestAnimationFrame(draw);

          player.analyserNode.getByteTimeDomainData(dataArray);

          const canvas = document.querySelector(".visualizer");
          const canvasCtx = canvas.getContext("2d");
          const WIDTH = canvas.width,
          HEIGHT = canvas.height;
          canvasCtx.fillStyle = "rgb(0 0 0)";
          canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

          canvasCtx.lineWidth = 1;
          canvasCtx.strokeStyle = "#228B22";

          canvasCtx.beginPath();

          const sliceWidth = (WIDTH * 1.0) / bufferLength;
          let x = 0;

          for (let i = 0; i < bufferLength; i++) {
            const v = dataArray[i] / 128.0;
            const y = (v * HEIGHT) / 2;

            if (i === 0) {
              canvasCtx.moveTo(x, y);
            } else {
              canvasCtx.lineTo(x, y);
            }

            x += sliceWidth;
          }

          canvasCtx.lineTo(WIDTH, HEIGHT / 2);
          canvasCtx.stroke();
        }

        draw();
      };

      window.changeVolume = function changeVolume(e) {
        player.volume(document.querySelector("#range").value);
      };
      window.pause = async function pause() {
        await player.pause();
      };
      window.continuePlay = function continuePlay() {
        player.continue();
      };
    </script>
  </body>
</html>
